/*
 * @lc app=leetcode.cn id=438 lang=swift
 *
 * [438] 找到字符串中所有字母异位词
 */

// @lc code=start
class Solution {
    func countRepresent(_ string: ArraySlice<Character>) -> [Int]{
        var result = Array<Int>.init(repeating: 0, count: 26)
        let value = Character("a").asciiValue!
        for c in string {
            result[Int(c.asciiValue! - value)] += 1
        }
        return result
    }
    
    func findAnagrams(_ s: String, _ p: String) -> [Int] {
        let stringArray = Array(s)
        let patternArray = Array(p)
        
        guard stringArray.count >= patternArray.count else {
            return []
        }
        var result = [Int]()
        let patternLength = patternArray.count
        let patternCounts = countRepresent(patternArray[...])
        let characterArray = Array(s)
        var compareCounts = countRepresent(characterArray[0 ..< patternLength])
        if patternCounts == compareCounts {
            result.append(0)
        }
        
        
        guard s.count - patternLength >= 1 else {
            return result
        }
        
        let aAsciiValue = Character("a").asciiValue!
        for i in 1 ... s.count - patternLength {
            
            let previousCharacter = stringArray[i - 1]
            let previousIndex = Int(previousCharacter.asciiValue! - aAsciiValue)
            compareCounts[previousIndex] -= 1
            let lastCharacter = stringArray[i - 1 + patternLength]
            let lastIndex = Int(lastCharacter.asciiValue! - aAsciiValue)
            compareCounts[lastIndex] += 1
            if patternCounts == compareCounts {
                result.append(i)
            }
        }
        
        return result
    }
}


// @lc code=end

